package voidlib;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import models.RequestStatus;

/**
 * @author nevidimov
 */
public abstract class VoidModel {
    
    public abstract VoidMapper getMapper();
    protected abstract String _getModelId();
    
    public int save() {
        Field[] fields = this.getClass().getDeclaredFields();
        HashMap<String, Object> vals = new HashMap<String, Object>();
        for (int i = 0; i < fields.length; i++) {
            String name = fields[i].getName();
            if (!name.startsWith("_")) {
                continue;
            }
            try {
                vals.put(name.substring(1), fields[i].get(this)); 
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return this.getMapper().save(vals, _getModelId());
    }
    
    public void setField(String name, Object value) {
        try {
            Field field = this.getClass().getField(name);
            Class<?> fieldType = field.getType();
            if (VoidMapper.isWrapperType(fieldType) || fieldType.isPrimitive() || fieldType == String.class) {
                field.set(this, value);
            } else {
                Class<?> cl = field.getType();
                Method method = cl.getDeclaredMethod("valueOf", String.class);
                Object result = method.invoke(cl, value);
                field.set(this, result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            
        }
    }
    
    public <T> T fetch(int id) {
        try {
            return this.getMapper().fetch(id);
        } catch (Exception e) {
            e.printStackTrace();;
        }
        return null;
    }

}
